<template>
  <div class="main-container">
    <!-- 使用工具栏组件 -->
    <Toolbar :is-maximized="isMaximized" :are-other-buttons-disabled="areOtherButtonsDisabled" @setting="handleSetting"
      @lock="handleLock" @minimize="minimizeWindow" @toggle-maximize="toggleMaximize" @close="closeWindow" />

    <!-- 聊天窗口 -->
    <div class="chat-window">
      <!-- 消息列表 -->
      <div class="message-list-container" ref="messageListRef" @scroll="handleScroll">
        <div class="message-list">
          <div v-for="(msg, index) in messages" :key="index" class="message-item"
            :class="{ 'user-message': msg.role === msg.role, 'ai-message': msg.role === 'AI助手' }">
            <div class="message-content">
              <div class="message-header">
                <span class="sender">{{ msg.role === 'AI助手' ? 'AI助手' : msg.role }}</span>
                <span class="time">{{ msg.time }}</span>
              </div>
              <div class="message-text">{{ msg.content }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 消息输入框 -->
      <div class="message-input">
        <el-input v-model="newMessage" type="textarea" :autosize="{ minRows: 4 }" placeholder="输入消息..."
          @keyup.enter="sendMessage" :disabled="isSending">
          <template #append>
            <el-button @click="sendMessage" :loading="isSending">
              <el-icon>
                <Position />
              </el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>
  </div>

  <!-- 设置弹窗 -->
  <SettingDialog v-model:visible="dialogVisible" />
</template>

<script setup lang="ts">
import { ref, nextTick, watch, onMounted, onUnmounted } from 'vue'
import SettingDialog from '@layout/setting/index.vue'
import Toolbar from '@layout/tabbar/index.vue'
import { Position } from '@element-plus/icons-vue'
import { getToken, reqChat } from '@api/chat'
import type { ReqChatTypes } from '@/types/chat'
import { formatTime, formatTimeString } from '@utils/index'
import { useSettingStore } from '@store/settingStore'

// 消息列表
interface ChatMessage {
  role: 'user' | 'AI助手'
  content: string
  time: string
}

const messages = ref<ChatMessage[]>([])
const newMessage = ref('')
const isSending = ref(false)
const sessionId = ref('') // 保存会话ID，云算力非必传

const SCROLL_THRESHOLD = 50;
const shouldAutoScroll = ref(true)
const messageListRef = ref<HTMLElement | null>(null)

// 滚动到顶部加载相关变量
const TOP_SCROLL_THRESHOLD = 100; // 距离顶部100px时触发加载
const isLoading = ref(false); // 加载状态
const hasMore = ref(true); // 是否还有更多数据
const nextCursor = ref<{ date: string; skip: number } | null>(null); // 分页游标
const firstLoad = ref(true); // 是否首次加载


// 滚动事件处理
const handleScroll = () => {
  if (!messageListRef.value) return;
  const { scrollTop, scrollHeight, clientHeight } = messageListRef.value;

  // 判断是否滚动到底部（允许1px的误差）
  shouldAutoScroll.value = scrollHeight - scrollTop - clientHeight <= SCROLL_THRESHOLD;

  // 新增：判断是否滚动到顶部（距离顶部小于阈值）
  if (scrollTop <= TOP_SCROLL_THRESHOLD && !isLoading.value && hasMore.value && !firstLoad.value) {
    loadMoreHistory();
  }
};

// 滚动到底部
const scrollToBottom = (immediate = false) => {
  nextTick(() => {
    if (!messageListRef.value || !shouldAutoScroll.value) return;
    messageListRef.value.scrollTo({
      top: messageListRef.value.scrollHeight,
      behavior: immediate ? 'auto' : 'smooth'
    });
  });
};

// 加载更多历史消息
const loadMoreHistory = async () => {
  if (isLoading.value || !hasMore.value) return;
  try {
    isLoading.value = true;
    // 确保游标可序列化
    const safeCursor = nextCursor.value 
      ? { 
          date: String(nextCursor.value.date), 
          skip: Number(nextCursor.value.skip) 
        } 
      : null;

    const params = {
      storagePath,
      pageSize: 20,
      cursor: safeCursor, // 使用处理后的游标
      isInitial: false
    };

    // 添加序列化检查
    const { data, nextCursor: cursor, hasMore: more } = 
      await window.electron.ipcRenderer.invoke('load-chat', JSON.parse(JSON.stringify(params)));

    // 处理返回数据
    messages.value = [
      ...data.map(msg => ({
        ...msg,
        // 确保时间格式统一
        time: typeof msg.time === 'string' 
          ? formatTimeString(msg.time) 
          : formatTimeString(new Date(msg.time).toISOString())
      })),
      ...messages.value
    ];
    
    nextCursor.value = cursor;
    hasMore.value = more;
    firstLoad.value = false; // 首次加载已完成
  } catch (error) {
    console.error('加载历史消息失败:', error);
  } finally {
    isLoading.value = false;
  }
};

// 监听消息变化
watch(() => messages.value, () => {
  scrollToBottom();
}, { deep: true });

// 控制工具栏按钮是否禁用
const areOtherButtonsDisabled = ref(false)

// 窗口状态
const isMaximized = ref(false)

// 控制弹窗显示
const dialogVisible = ref(false)

const settingStore = useSettingStore()

// 打开设置弹窗
const handleSetting = () => {
  dialogVisible.value = true
}

// 窗口控制
const minimizeWindow = () => {
  window.electron.ipcRenderer.invoke('minimize-window')
}

const toggleMaximize = () => {
  isMaximized.value = !isMaximized.value
  window.electron.ipcRenderer.invoke('toggle-maximize-window', isMaximized.value)
}

//关闭窗口，从持久化存储中读取关闭窗口是退出还是隐藏到托盘
const closeWindow = () => {
  const exitOnClose = settingStore.settings.general.exitOnClose;
  if (exitOnClose) {
    window.electron.ipcRenderer.invoke('close-window')
  } else {
    window.electron.ipcRenderer.invoke('hide-to-tray')
    //路由到能量球页面，并隐藏当前窗口到托盘，暂无时间实现，暂时注释掉
    // router.push('/energy-ball')
  }
}

//锁屏时，将是否置顶设置传给electron
const isLocked = ref(false)
const handleLock = async () => {
  const awayOnTop = settingStore.settings.general.awayOnTop;
  isLocked.value = !isLocked.value
  areOtherButtonsDisabled.value = isLocked.value
  window.electron.ipcRenderer.invoke('lock-window', isLocked.value, awayOnTop)
  //锁定后，将窗口变为大小不可修改
  window.electron.ipcRenderer.invoke('set-window-resizable', !isLocked.value)

}

// 获取消息的存储路径
const storagePath = settingStore.settings.general.savePath;

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim() || isSending.value) return;

  try {
    isSending.value = true;
    const userMessage = newMessage.value;
    const currentTime = new Date().toISOString();
    let username = localStorage.getItem('username') as "user" | "AI助手" || 'user';
    messages.value.push({
      role: username,
      content: userMessage,
      time: formatTimeString(currentTime)
    });

    // 滚动到底部并重置标志位以允许自动滚动
    shouldAutoScroll.value = true;
    scrollToBottom(true);
    // 将对话信息存到本地
    window.electron.ipcRenderer.invoke('save-chat', {
      role: username,
      content: userMessage,
      time: currentTime
    }, storagePath);
    // 后续添加逻辑：对话信息同步持久化到后台DB
    newMessage.value = '';

    // 获取token
    const resData = await getToken(username);
    let token = resData.data.token

    // 准备请求数据（确保类型匹配）
    const requestData: ReqChatTypes = {
      openId: 123,
      token: token,
      question: userMessage,
      sessionId: sessionId.value || undefined
    };

    // 调用API（确保reqChat函数接收ReqChatTypes参数）
    const response = await reqChat(requestData);

    if (response.code === 0 && response.data.code === 200) {
      // 保存会话ID供下次使用
      sessionId.value = response.data.sessionId;

      // 添加AI回复到聊天区
      const aiResponse = response.data.response;
      const aiTime = new Date().toISOString();;
      messages.value.push({
        role: 'AI助手',
        content: aiResponse,
        time: formatTimeString(aiTime)
      });
      // 机器人的回复内容存到本地
      window.electron.ipcRenderer.invoke('save-chat', {
        role: 'AI助手',
        content: aiResponse,
        time: aiTime,
      }, storagePath);
      // 机器人回复一样需要滚动到底部并重置标志位以允许自动滚动
      shouldAutoScroll.value = true;
    } else {
      throw new Error(response.msg || '请求失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    // 添加错误提示到聊天区
    messages.value.push({
      role: 'AI助手',
      content: '抱歉，我暂时无法处理您的请求，请稍后再试。',
      time: formatTime(new Date())
    })
  } finally {
    isSending.value = false
  }
}

// 加载聊天记录
const loadChat = async (isInitial = false) => {
  if (isLoading.value || (!isInitial && !hasMore.value)) return;

  isLoading.value = true;
  try {
    const params = {
      storagePath,
      pageSize: 20,
      cursor: isInitial ? null : nextCursor.value,
      isInitial: isInitial
    };

    const { data, nextCursor: cursor, hasMore: more } =
      await window.electron.ipcRenderer.invoke('load-chat', params);

    if (isInitial) {
      messages.value = data.map(msg => ({ ...msg, time: formatTimeString(msg.time) }));
    } else {
      // 滚动加载时插入到顶部（历史消息）
      messages.value = [...data.map(msg => ({ ...msg, time: formatTimeString(msg.time) })), ...messages.value];
    }

    nextCursor.value = cursor;
    hasMore.value = more;
    firstLoad.value = false; // 标记为已完成首次加载
  } catch (error) {
    console.error('加载失败:', error);
  } finally {
    isLoading.value = false;
  }
};

// 移除滚动事件监听
onUnmounted(() => {
  if (messageListRef.value) {
    messageListRef.value.removeEventListener('scroll', handleScroll);
  }
});

onMounted(() => {
  // 加载本地聊天记录
  loadChat(true);

  // 滚动到底部并重置标志位以允许自动滚动
  shouldAutoScroll.value = true;
  scrollToBottom(true);

  // 添加滚动事件监听
  if (messageListRef.value) {
    messageListRef.value.addEventListener('scroll', handleScroll);
  }
});

</script>

<style scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
  overflow: hidden;
  border-radius: 10px;
}

.chat-window {
  height: calc(100vh - 40px);
  min-height: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9f9f9;
  scroll-behavior: smooth;
  min-height: 0;
}

.message-list-container {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: transparent transparent;
  transition: scrollbar-color 0.1s;
}

.message-list-container:hover {
  scrollbar-color: #c1c1c1 transparent;
}

.message-list-container::-webkit-scrollbar {
  width: 6px;
  background: transparent;
}

.message-list-container::-webkit-scrollbar-thumb {
  background: transparent;
  border-radius: 3px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background-clip: padding-box;
  transition: background 0.1s;
}

.message-list-container:hover::-webkit-scrollbar-thumb {
  background: #c1c1c1;
}

.message-list {
  display: flex;
  flex-direction: column;
  min-height: min-content;
  scroll-behavior: smooth;
}

.message-item {
  display: flex;
  margin-bottom: 1.2rem;
}

.message-content {
  max-width: 80%;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 13px;
}

.sender {
  font-weight: bold;
  color: #606266;
}

.time {
  font-size: 12px;
  color: #909399;
}

.message-text {
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 15px;
  line-height: 1.6;
  word-break: break-word;
  white-space: pre-wrap;
  overflow-wrap: anywhere;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9f9f9;
}

.message-item.user-message {
  justify-content: flex-end;
}

.message-item.ai-message {
  justify-content: flex-start;
}

.user-message .message-text {
  background-color: #C9E7FF;
  color: #1a1a1a;
  border-radius: 12px 0 12px 12px;
}

.ai-message .message-text {
  background-color: #E4E7EB;
  color: #1a1a1a;
  border-radius: 0 12px 12px 12px;
}

/* 消息输入区域 */
.message-input {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: white;
}

.message-input .el-textarea__inner {
  font-size: 15px;
  line-height: 1.6;
  padding-top: 12px;
  padding-bottom: 12px;
}

.message-input .el-button {
  height: 100%;
}
</style>